#!/usr/bin/env python3
import json
import http.server
import socketserver
from urllib.parse import urlparse, parse_qs

class APIHandler(http.server.BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
    
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        
        if self.path == '/health':
            response = {'status': 'OK', 'message': 'API server running on port 8080'}
        else:
            response = {'message': 'API Server', 'path': self.path, 'port': 8080}
        
        self.wfile.write(json.dumps(response).encode())
    
    def do_POST(self):
        if self.path == '/api/auth/login':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            
            try:
                data = json.loads(post_data.decode('utf-8'))
                print(f'Login request: {data}')
                
                self.send_response(200)
                self.send_header('Content-type', 'application/json')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                
                response = {
                    'success': True,
                    'message': '登录成功',
                    'data': {
                        'user': {'id': 1, 'email': 'admin@example.com', 'name': 'Admin'},
                        'token': 'test-token-123'
                    }
                }
                
                self.wfile.write(json.dumps(response).encode())
            except Exception as e:
                self.send_response(400)
                self.send_header('Content-type', 'application/json')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                
                response = {'success': False, 'message': str(e)}
                self.wfile.write(json.dumps(response).encode())
        else:
            self.send_response(404)
            self.send_header('Content-type', 'application/json')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            response = {'success': False, 'message': 'Endpoint not found'}
            self.wfile.write(json.dumps(response).encode())

if __name__ == '__main__':
    PORT = 8080
    
    try:
        with socketserver.TCPServer(("", PORT), APIHandler) as httpd:
            print(f"🚀 API server started on http://localhost:{PORT}")
            print(f"📍 Health check: http://localhost:{PORT}/health")
            print(f"🔐 Login endpoint: POST http://localhost:{PORT}/api/auth/login")
            httpd.serve_forever()
    except Exception as e:
        print(f"❌ Server failed to start: {e}")